package com.pangus.ipc.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pangus.ipc.dto.domain.IpcDataDto;
import com.pangus.ipc.dto.domain.LoginDto;
import com.pangus.ipc.util.JsoupUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class MesIpcService {



    public IpcDataDto ipcLoginType1(LoginDto loginDto) throws Exception {
        Connection connect = Jsoup.connect(loginDto.getVersionUrl());
        Map<String, String> cookiesMap = getCookiesMap1(loginDto.getLoginUrl(), loginDto.getUserName(), loginDto.getPassWord());
        if(cookiesMap.size()==0){
            throw new Exception("登录出错");
        }
        JsoupUtils.setCookies(connect, cookiesMap);
        Document document = connect.get();


        Map<String, String> map = new HashMap<>();
        map.put("REQ", "{\"MODULE\":\"CONFIGMODEL\",\"SESSION\":\"FROMIE\",\"OPERATION\":\"GET\",\"PARAMETER\":" +
                "{\"MDVR\":{\"ETHERNET\":{\"PIP\":{\"IPADDR\":\"?\",\"SUBMASK\":\"?\",\"GATEWAY\":\"?\"},\n" +
                "\"DNS\":{\"PDNS\":\"?\",\"ADNS\":\"?\"},\"IPMODE\":\"?\",\"DNSMODE\":\"?\"},\"KEYS\":{\"MAC\":\"?\"}}}}");
        Connection.Response execute = Jsoup.connect(loginDto.getMacUrl()).data(map).cookies(cookiesMap).method(Connection.Method.POST).execute();
        String body = execute.body();
        return dealWithData1(document.body().toString(), body,null);
    }

    public IpcDataDto ipcLoginType2(LoginDto loginDto) throws Exception {
        String macData="";
        String serialNum="";
        String version="";
        String terminalId="";
        String imei="";
        String mcuVersion = "";
        String mediaAddress = "";
        Map<String, String> cookiesMap = getCookiesMap2(loginDto.getLoginUrl(), loginDto.getUserName(), loginDto.getPassWord(),1,1);
        if(cookiesMap.size()==0){
            throw new Exception("登录出错");
        }else if(cookiesMap.get("sessionId")==null||cookiesMap.get("sessionId").equals("")){
            throw new Exception("登录出错");
        }
        //获取序列号
        try {
            IpcDataDto ipcDataDto = getType2VerAndSer(loginDto);
            serialNum = ipcDataDto.getSerialNum();
            version = ipcDataDto.getVersion();
        }catch (Exception e){
            throw new Exception("序列号serial获取发生错误："+e.getMessage());
        }
        //获取MCU版本号
        try {
            IpcDataDto verIpcData = getType2VersionMCU(loginDto, cookiesMap);
            mcuVersion = verIpcData.getMcuVersion();
        }catch (Exception e){
           e.printStackTrace();
        }

        //获取软件版本号
        try {
            loginDto.setVersionUrl(loginDto.getVersionUrl().replaceAll("version","newversion"));
            IpcDataDto verIpcData = getType2Version(loginDto, cookiesMap);
            version=verIpcData.getVersion();
        }catch (Exception e){
            if(version==null||"".equals(version)||" ".equals(version)) {
                throw new Exception("版本号获取发生错误：" + e.getMessage());
            }
        }

        //获取注册服务器地址
        try {
            loginDto.setVersionUrl(loginDto.getVersionUrl().replaceAll("newversion","serverstatus"));
            IpcDataDto verIpcData = getType2MediaAddress(loginDto, cookiesMap);
            mediaAddress=verIpcData.getMediaAddress();
        }catch (Exception e){
            e.printStackTrace();
        }


        //获取MAC
        try {
            IpcDataDto ipcDataDto = getType2Mac(loginDto,cookiesMap);
            macData=ipcDataDto.getMac();
            terminalId=ipcDataDto.getTerminalId();
        }catch (Exception e){
            throw new Exception("mac获取发生错误："+e.getMessage());
        }

        try{
            imei=getType2Imei(loginDto,cookiesMap);
        }catch (Exception e){
            System.out.println("IMEI号获取发生错误："+e.getMessage());
            imei=null;
        }
        IpcDataDto ipcDataDto = new IpcDataDto();
        ipcDataDto.setMac(macData);
        ipcDataDto.setSerialNum(serialNum);
        ipcDataDto.setVersion(version);
        ipcDataDto.setTerminalId(terminalId);
        ipcDataDto.setImei(imei);
        ipcDataDto.setMcuVersion(mcuVersion);
        ipcDataDto.setMediaAddress(mediaAddress);
        return ipcDataDto;
    }

    public String getType2Imei(LoginDto loginDto,Map<String, String> cookiesMap)throws Exception{
        Connection connect = Jsoup.connect(loginDto.getImeiUrl());
        JsoupUtils.setCookies(connect,cookiesMap);
        String html = connect.get().body().html();
        JSONObject parse = (JSONObject) JSONObject.parse(html);
        JSONObject data = parse.getJSONObject("data");
        JSONArray chatData = data.getJSONObject("_3G4G").getJSONArray("3GINFO");
        JSONObject jsonObject = chatData.getJSONObject(0);
        return jsonObject.getString("IMEI");
    }

    public IpcDataDto getType2VerAndSer(LoginDto loginDto) throws Exception {
        Connection serNumConnect = Jsoup.connect(loginDto.getSerNumUrl());
        Document serNumDocument = serNumConnect.get();
        String serNumData = serNumDocument.body().html();
        JSONObject serParse = (JSONObject) JSONObject.parse(serNumData);
        JSONObject dataObject = serParse.getJSONObject("data");
        String serNum = dataObject.getString("securitynum");
        JSONObject versionObject = dataObject.getJSONObject("version");
        String version = versionObject.getString("MAIN");
        IpcDataDto ipcDataDto=new IpcDataDto();
        ipcDataDto.setVersion(version);
        ipcDataDto.setSerialNum(serNum);
        return ipcDataDto;
    }
    public IpcDataDto getType2VersionMCU(LoginDto loginDto,Map<String, String> cookiesMap)throws Exception{
        IpcDataDto ipcDataDto = new IpcDataDto();
        Connection verConnect = Jsoup.connect(loginDto.getVersionUrl());
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();
        String verData = verDocument.body().html();
        JSONObject parse = (JSONObject) JSONObject.parse(verData);
        JSONObject data = parse.getJSONObject("data");
        String mcu = data.getString("MCU");
        ipcDataDto.setMcuVersion(mcu);
        return ipcDataDto;
    }

    public IpcDataDto getType2Version(LoginDto loginDto,Map<String, String> cookiesMap)throws Exception{
        IpcDataDto ipcDataDto = new IpcDataDto();
        Connection verConnect = Jsoup.connect(loginDto.getVersionUrl());
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();
        String verData = verDocument.body().html();
        JSONObject parse = (JSONObject) JSONObject.parse(verData);
        JSONObject data = parse.getJSONObject("data");
        String main = data.getString("MAIN");
        ipcDataDto.setVersion(main);
        return ipcDataDto;
    }

    public IpcDataDto getType2MediaAddress(LoginDto loginDto,Map<String, String> cookiesMap)throws Exception{
        IpcDataDto ipcDataDto = new IpcDataDto();
        Connection verConnect = Jsoup.connect(loginDto.getVersionUrl());
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();
        String verData = verDocument.body().html();
        JSONObject parse = (JSONObject) JSONObject.parse(verData);
        JSONObject data = parse.getJSONObject("data");
        JSONArray servers  = data.getJSONArray("servers");
       String str = servers.getString(0);
        JSONObject cipParse = (JSONObject) JSONObject.parse(str);
        ipcDataDto.setMediaAddress(cipParse.getString("cip"));
        return ipcDataDto;
    }


    public IpcDataDto getType2Mac(LoginDto loginDto,Map<String, String> cookiesMap ) throws Exception {
        IpcDataDto ipcDataDto = new IpcDataDto();
        Connection macConnect = Jsoup.connect(loginDto.getMacUrl());
        JsoupUtils.setCookies(macConnect, cookiesMap);
        Document macDocument = macConnect.get();
        String macData = macDocument.body().html();
        JSONObject macParse = (JSONObject) JSONObject.parse(macData);
        JSONObject dataObject = macParse.getJSONObject("data");
        JSONObject mdvrObject = dataObject.getJSONObject("PARAMETER").getJSONObject("MDVR");
        String mac = mdvrObject.getJSONObject("KEYS").getString("MAC");
        JSONObject psiObject = mdvrObject.getJSONObject("PSI");
        if(psiObject!=null){
            JSONArray piArray = psiObject.getJSONArray("PI");
            JSONObject index1 = (JSONObject) piArray.get(0);
            String tid = index1.getString("TID");
            ipcDataDto.setTerminalId(tid);
        }
        ipcDataDto.setMac(mac.replaceAll(":","").replaceAll("：",""));

        return ipcDataDto;
    }

    public IpcDataDto dealWithData1(String verAndSerData, String macData,String terminalNoData){
        IpcDataDto ipcDataDto = new IpcDataDto();
        //开始解析软件版本信息和序列号信息
        String replaceAll = verAndSerData
                .replaceAll("<body>", "")
                .replaceAll("</body>", "")
                .replaceAll("\r|\n","");
        JSONObject parse = (JSONObject) JSONObject.parse(replaceAll);
        String serialNum = parse.getString("serialNum");
        String software = parse.getString("software");
        ipcDataDto.setSerialNum(serialNum);
        ipcDataDto.setVersion(software);
        //解析结束

        //开始解析mac地址信息
        macData=macData.replaceAll("\r|\n","");
        JSONObject macJson = (JSONObject) JSON.parse(macData);
        JSONObject parameter = macJson.getJSONObject("PARAMETER");
        JSONObject mdvr = parameter.getJSONObject("MDVR");
        JSONObject keys = mdvr.getJSONObject("KEYS");
        String mac = keys.getString("MAC");
        ipcDataDto.setMac(mac.replaceAll(":","").replaceAll("：",""));
        return ipcDataDto;
    }


    public Map<String,String> getCookiesMap1(String loginUrl,String userCode,String passWord) throws IOException {
        Map<String,String> map=new HashMap<>();
        if(userCode==null){
            userCode="";
        }
        if(passWord==null){
            passWord="";
        }
        map.put("username",userCode);
        map.put("userpwd",passWord);
        Connection.Response execute = Jsoup.connect(loginUrl).data(map).method(Connection.Method.GET).execute();
        return execute.cookies();
    }

    public Map<String,String> getCookiesMap2(String loginUrl,String userCode,String passWord,Integer language,Integer autoLogin) throws IOException {
        Map<String,String> map=new HashMap<>();
        if(userCode==null){
            userCode="";
        }
        if(passWord==null){
            passWord="";
        }
        map.put("username",userCode);
        map.put("password",passWord);
        if(language!=null){
            map.put("language",String.valueOf(language));
        }
        if(autoLogin!=null){
            map.put("autoLogin",String.valueOf(autoLogin));
        }
        Connection.Response execute = Jsoup.connect(loginUrl).data(map).method(Connection.Method.GET).execute();
        return execute.cookies();
    }
    public String changeCookiesToString(Map<String,String> cookies){
        StringBuilder res=new StringBuilder();
        for (String key:cookies.keySet()){
            String value = cookies.get(key);
            res.append(key+"="+value+";");
        }

        return  res.length() > 0 ? res.deleteCharAt(res.length() - 1).toString() : "";
    }
}
